﻿using Coldairarrow.Business.PB;
using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.IBusiness;
using Coldairarrow.IBusiness.DTO;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.PB
{
    [Route("/PB/[controller]/[action]")]
    public partial class PB_MaterialController : BaseApiController
    {
        #region DI
        private readonly RedisOptions _redisOptions; //1.声明实体
        private readonly MongoDBOptions _mongodbOptions;

        public PB_MaterialController(IPB_MaterialTypeBusiness pB_MaterialTypeBus, IPB_MaterialBusiness pB_MaterialBus, IServiceProvider provider, IOperator op, IOptions<RedisOptions> redisOptions, IOptions<MongoDBOptions> mongodbOptions)
        {
            _pB_MaterialTypeBus = pB_MaterialTypeBus;
            _pB_MaterialBus = pB_MaterialBus;
            _provider = provider;
            _Op = op;
            _redisOptions = redisOptions.Value;//3.赋值
            _mongodbOptions = mongodbOptions.Value;
        }

        IPB_MaterialBusiness _pB_MaterialBus { get; }
        IPB_MaterialTypeBusiness _pB_MaterialTypeBus { get; }

        IServiceProvider _provider { get; }

        IOperator _Op { get; }


        #endregion

        #region 获取

        [HttpPost]
        public async Task<PageResult<PB_Material>> GetDataList(PageInput<PBMaterialConditionDTO> input)
        {
            return await _pB_MaterialBus.GetDataListAsync(input);
        }
        /// <summary>
        /// PDA补码定位物料
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_Material>> GetDataListByPDA(PageInput<PDAMaterialInputDTO> input)
        {
            return await _pB_MaterialBus.GetDataListByPDAAsync(input);
        }
        /// <summary>
        /// 通过物料ID获取同一类型的所有物料
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_MaterialStockNumberDTO>> ThroughMaterialGetDataList(PageInput<QueryPBMaterialType> input)
        {
            return await _pB_MaterialBus.ThroughMaterialGetDataList(input);
        }
        [HttpPost]
        public async Task<PageResult<PB_Material>> GetDataListByHasRef(PageInput<ConditionDTO> input)
        {
            return await _pB_MaterialBus.GetDataListByHasRefAsync(input);
        }

        [HttpPost]
        public async Task<List<PB_Material>> GetAllDataList()
        {
            return await _pB_MaterialBus.GetDataListAsync();
        }


        [HttpPost]
        public async Task<MaterialProductDTO> GetTheData(IdInputDTO input)
        {
            return await _pB_MaterialBus.GetTheDataAsync(input.id);
        }

        [HttpPost] 
        public async Task<List<PB_MaterialListDTO>> Selectid(string ID)
        {
            var res = await _pB_MaterialBus.Selectid(ID);
            return res;
        }
        [HttpPost]
        public async Task<List<PB_Material>> GetQueryData(SelectQueryDTO search)
        {
            return await _pB_MaterialBus.GetQueryData(search);
        }
        /// <summary>
        /// 返回数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]

        public async Task<List<PB_MaterialPricDTOList>> GetDataListDto(PageInput<ConditionDTO> input)
        {
            return await _pB_MaterialBus.GetDataListDTOAsync(input);
        }

        /// <summary>
        /// 生产订单添加选择物料明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_MaterialListData>> GetDataSelectList(PageInput<ConditionDTO> input)
        {
            return await _pB_MaterialBus.GetDataSelectAsync(input);
        }

        /// <summary>
        /// 生产任务单有源选择物料信息
        /// </summary>
        /// <param name="input"></param>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_MaterialDataSelectList>> GetDataSelectListsAsync(PageInput<PBMaterialConditionDTO> input, string ParentId)
        {
            return await _pB_MaterialBus.GetDataSelectListAsync(input,ParentId);
        }

        /// <summary>
        /// 外协加工根据生产任务带出物料信息
        /// </summary>
        /// <param name="input"></param>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_MaterialDataSelectList>> GetDataSelectProductionListsAsync(PageInput<PBMaterialConditionDTO> input, string ParentId)
        {
            return await _pB_MaterialBus.GetDataSelectProductionListsAsync(input, ParentId);
        }



        [HttpPost]
        public async Task<PageResult<PB_MaterialListDTO>> QueryDataList(PageInput<PBMaterialConditionDTO> input)
        {
            return await _pB_MaterialBus.QueryDataListAsync(input);
        }
        /// <summary>
        /// 显示仓库库位库存
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_MaterialStockDTO>> GetMaterialStockDataList(PageInput<PBMaterialConditionDTO> input)
        {
            return await _pB_MaterialBus.GetMaterialStockDataListAsync(input);
        }
        /// <summary>
        /// 根据仓库带出物料
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_MaterialStockDTO>> GetMaterialStockDataLists(PageInput<PBMaterialConditionDTO> input)
        {
            return await _pB_MaterialBus.GetMaterialStockDataListAsyncs(input);
        }

        [HttpGet]
        public async Task<PB_Material> GetByBarcode(string barcode)
        {
            return await _pB_MaterialBus.GetByBarcode(barcode);
        }
        [HttpGet]
        public async Task<PB_Material> GetByCode(string code)
        {
            return await _pB_MaterialBus.GetByCode(code);
        }


        /// <summary>
        /// 物料档案选择隶属成品
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_Material>> GetMaterialProductList(PageInput<PBMaterialConditionDTO> input)
        {
            return await _pB_MaterialBus.GetMaterialProductListAsync(input);
        }

        /// <summary>
        /// 物料数据导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<AjaxResult> Import(IFormFile file)// file
        {
            string ReturnValue = string.Empty;
            //定义一个bool类型的变量用来做验证
            bool flag = true;
            try
            {
                #region 检查文件
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存
                var Data = new List<PB_Material>();
                var liststr = new List<string>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum + 1;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");

                }
                #endregion
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < sheet.LastRowNum; j++)
                        {
                            //if ((j == 4 || j == 5) || (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0))
                            //{
                            //    //return Error(ReturnValue += $"注意第{i + 1}行,第{j + 1}列数据为空。");
                            //}
                            //else
                            //if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                            //{
                            //    flag = false;
                            //    return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                            //}
                            if (j == 3)
                            {
                                if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                                {
                                    flag = false;
                                    return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                                }
                            }
                            else if (j == 4)
                            {
                                if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                                {
                                    flag = false;
                                    return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                                }
                            }
                        }
                    }
                }
                #endregion
                if (flag)
                {
                    //获取物料类型id、单位组
                    List<tmpMaterialTypeDTO> _mtype = new List<tmpMaterialTypeDTO>(); 
                    List<tmpUnitGroupDTO> _ugrp = new List<tmpUnitGroupDTO>();
                    for (int i = 1; i < CountRow; i++)
                    {
                        var row = sheet.GetRow(i);
                        if (_mtype.Count(x => x.Code.Equals(row.GetCell(3).ToString())) < 1)
                        {
                            tmpMaterialTypeDTO tmp = new tmpMaterialTypeDTO()
                            {
                                Code = row.GetCell(3).ToString()
                            };
                            _mtype.Add(tmp);
                        }
                        if (_ugrp.Count(x => x.Name.Equals(row.GetCell(4).ToString())) < 1)
                        {
                            tmpUnitGroupDTO tmp = new tmpUnitGroupDTO()
                            {
                                Name = row.GetCell(4).ToString(),
                                Units = new List<tmpUnit>()
                                {
                                    new tmpUnit(){Name=row.GetCell(5).ToString() },
                                    new tmpUnit(){Name=row.GetCell(6).ToString() },
                                    new tmpUnit(){Name=row.GetCell(7).ToString() },
                                    new tmpUnit(){Name=row.GetCell(8).ToString() }
                                }
                            };
                            _ugrp.Add(tmp);
                        }
                    }
                    _mtype = _pB_MaterialTypeBus.GetTheDataByCode(_mtype);
                    _ugrp = _pB_MaterialTypeBus.GetTheDataByName(_ugrp);

                    for (int i = 1; i < CountRow; i++)
                    {
                        //实例化实体对象
                        PB_Material commodity = new PB_Material();
                        bool bname = false;
                        var row = sheet.GetRow(i);
                        if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                        {
                            commodity.Id = IdHelper.GetId();
                            commodity.CreatorId = _Op.UserId; //"Admin";//_Op.UserId;
                            commodity.CreateTime = DateTime.Now;
                            commodity.Name = row.GetCell(0).ToString();

                        }
                        if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                        {
                            commodity.Code = row.GetCell(1).ToString().Replace("\t", "");
                        }
                        if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                        {
                            commodity.SimpleName = row.GetCell(2).ToString();
                        }
                        if (row.GetCell(3) != null && row.GetCell(3).ToString().Trim().Length > 0)
                        {
                            //commodity.MaterialTypeId = row.GetCell(3).ToString();
                            try
                            {
                                commodity.MaterialTypeId = _mtype.FirstOrDefault(x => x.Code == row.GetCell(3).ToString()).Id;
                            }
                            catch
                            {
                                commodity.MaterialTypeId = "";
                            }
                        }
                        if (row.GetCell(4) != null && row.GetCell(4).ToString().Trim().Length > 0)
                        {
                            try
                            {
                                commodity.UnitGroupId = _ugrp.FirstOrDefault(x => x.Name == row.GetCell(4).ToString()).Id;
                            }
                            catch 
                            {
                                commodity.UnitGroupId = "";
                            }
                            //commodity.UnitGroupId = row.GetCell(4).ToString();
                        }
                        var u1 = _ugrp.FirstOrDefault(x => x.Name == row.GetCell(4).ToString()).Units;
                        if (row.GetCell(5) != null && row.GetCell(5).ToString().Trim().Length > 0)
                        {
                            var model = u1.FirstOrDefault(x => x.Name == row.GetCell(5).ToString());
                            if (model != null)
                            {
                                commodity.storageId = model.Id;
                            }
                            else
                            {
                                commodity.storageId = "";
                            }
                            //commodity.storageId = row.GetCell(5).ToString();
                        }
                        if (row.GetCell(6) != null && row.GetCell(6).ToString().Trim().Length > 0)
                        {
                            var model = u1.FirstOrDefault(x => x.Name == row.GetCell(6).ToString());
                            if (model != null)
                            {
                                commodity.saleId = model.Id;
                            }
                            else
                            {
                                commodity.saleId = "";
                            }
                            //commodity.saleId = row.GetCell(6).ToString();
                        }
                        if (row.GetCell(7) != null && row.GetCell(7).ToString().Trim().Length > 0)
                        {
                            var model = u1.FirstOrDefault(x => x.Name == row.GetCell(7).ToString());
                            if (model != null)
                            {
                                commodity.purchaseId = model.Id;
                            }
                            else
                            {
                                commodity.purchaseId = "";
                            }
                        }
                        if (row.GetCell(8) != null && row.GetCell(8).ToString().Trim().Length > 0)
                        {
                            var model = u1.FirstOrDefault(x => x.Name == row.GetCell(8).ToString());
                            if (model != null)
                            {
                                commodity.productionId = model.Id;
                            }
                            else
                            {
                                commodity.productionId = "";
                            }
        }
                        if (row.GetCell(9) != null && row.GetCell(9).ToString().Trim().Length > 0)
                        {
                            commodity.ProcecureId = row.GetCell(9).ToString();
                        }
                        if (row.GetCell(10) != null && row.GetCell(10).ToString().Trim().Length > 0)
                        {
                            commodity.Spec = row.GetCell(10).ToString();
                        }
                        if (row.GetCell(11) != null && row.GetCell(11).ToString().Trim().Length > 0)
                        {
                            commodity.Max = Convert.ToDouble(row.GetCell(11).ToString());
                        }
                        if (row.GetCell(12) != null && row.GetCell(12).ToString().Trim().Length > 0)
                        {
                            commodity.Min = Convert.ToDouble(row.GetCell(12).ToString());
                        }
                        if (row.GetCell(13) != null && row.GetCell(13).ToString().Trim().Length > 0)
                        {
                            commodity.CusId = row.GetCell(13).ToString();
                        }
                        if (row.GetCell(14) != null && row.GetCell(14).ToString().Trim().Length > 0)
                        {
                            commodity.SupId = row.GetCell(14).ToString();
                        }
                        if (row.GetCell(15) != null && row.GetCell(15).ToString().Trim().Length > 0)
                        {
                            commodity.StorId = row.GetCell(15).ToString();
                        }
                        if (row.GetCell(16) != null && row.GetCell(16).ToString().Trim().Length > 0)
                        {
                            commodity.Price = Convert.ToDouble(row.GetCell(16).ToString());
                        }
                        if (row.GetCell(17) != null && row.GetCell(17).ToString().Trim().Length > 0)
                        {
                            commodity.NewPrice = Convert.ToDouble(row.GetCell(17).ToString());
                        }
                        if (row.GetCell(18) != null && row.GetCell(18).ToString().Trim().Length > 0)
                        {
                            commodity.MinPrice = Convert.ToDouble(row.GetCell(18).ToString());
                        }
                        if (row.GetCell(19) != null && row.GetCell(19).ToString().Trim().Length > 0)
                        {
                            commodity.MaxPrice = Convert.ToDouble(row.GetCell(19).ToString());
                        }
                        if (row.GetCell(20) != null && row.GetCell(20).ToString().Trim().Length > 0)
                        {
                            commodity.SettlePrice = Convert.ToDouble(row.GetCell(20).ToString());
                        }
                        if (row.GetCell(21) != null && row.GetCell(21).ToString().Trim().Length > 0)
                        {
                            commodity.Weight = Convert.ToDouble(row.GetCell(21).ToString());
                        }
                        if (row.GetCell(22) != null && row.GetCell(22).ToString().Trim().Length > 0)
                        {
                            commodity.Area = Convert.ToDouble(row.GetCell(22).ToString());
                        }
                        if (row.GetCell(23) != null && row.GetCell(23).ToString().Trim().Length > 0)
                        {
                            commodity.PackingSpec = row.GetCell(23).ToString();
                        }
                        if (row.GetCell(24) != null && row.GetCell(24).ToString().Trim().Length > 0)
                        {
                            commodity.Length = Convert.ToDouble(row.GetCell(24).ToString());
                        }
                        if (row.GetCell(25) != null && row.GetCell(25).ToString().Trim().Length > 0)
                        {
                            commodity.Width = Convert.ToDouble(row.GetCell(25).ToString());
                        }
                        if (row.GetCell(26) != null && row.GetCell(26).ToString().Trim().Length > 0)
                        {
                            commodity.Height = Convert.ToDouble(row.GetCell(26).ToString());
                        }
                        if (row.GetCell(27) != null && row.GetCell(27).ToString().Trim().Length > 0)
                        {
                            commodity.Estimate = Convert.ToDouble(row.GetCell(27).ToString());
                        }
                        if (row.GetCell(28) != null && row.GetCell(28).ToString().Trim().Length > 0)
                        {
                            commodity.PositionCode = row.GetCell(28).ToString();
                        }
                        if (row.GetCell(29) != null && row.GetCell(29).ToString().Trim().Length > 0)
                        {
                            commodity.Ofmaterial = row.GetCell(29).ToString();
                        }
                        if (row.GetCell(30) != null && row.GetCell(30).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(30).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsProduct = bname;
                            bname = false;
                        }
                        if (row.GetCell(31) != null && row.GetCell(31).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(31).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsNumber = bname;
                            bname = false;
                        }
                        if (row.GetCell(32) != null && row.GetCell(32).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(32).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsMine = bname;
                            bname = false;
                        }
                        if (row.GetCell(33) != null && row.GetCell(33).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(33).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsLabour = bname;
                            bname = false;
                        }
                        if (row.GetCell(34) != null && row.GetCell(34).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(34).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsQuantity = bname;
                            bname = false;
                        }
                        if (row.GetCell(35) != null && row.GetCell(35).ToString().Trim().Length > 0)
                        {
                            commodity.Remarks = row.GetCell(35).ToString();
                        }
                        if (row.GetCell(36) != null && row.GetCell(36).ToString().Trim().Length > 0)
                        {
                            commodity.PackageNum = Convert.ToDouble(row.GetCell(36).ToString());
                        }
                        if (row.GetCell(37) != null && row.GetCell(37).ToString().Trim().Length > 0)
                        {
                            commodity.ProductCode = row.GetCell(37).ToString();
                        }
                        if (row.GetCell(38) != null && row.GetCell(38).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(38).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsSingle = bname;
                            bname = false;
                        }
                        if (row.GetCell(39) != null && row.GetCell(39).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(34).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsVirtualkey = bname;
                            bname = false;
                        }
                        commodity.CreateTime = DateTime.Now;
                        commodity.IsBuy = false;
                        commodity.HasRef = false;
                        commodity.IsCruxMaterial = false;
                        commodity.IsKeyprice = false;//
                        commodity.IsStandard = false;
                        commodity.UsageStatus = true;
                        Data.Add(commodity);
                        liststr.Add(commodity.Code + "," + commodity.Name);
                    }

                    string SpaceString = "";
                    //判断导入的数据是否存在
                    var lists = _pB_MaterialBus.GetQueryable<PB_Material>().Where(x => liststr.Contains(x.Code + "," + x.Name));
                    if (lists.Count() > 0)
                    {
                        //物料编号和名称重复过滤 直接执行
                        //foreach (var remo in lists)
                        //{
                        //    var mdata = Data.Find(x => x.Code == remo.Code && x.Name == remo.Name);
                        //    if (mdata != null)
                        //    {
                        //        Data.Remove(mdata);
                        //    }

                        //}

                        return Error(ReturnValue = "导入的数据中有已存在数据库中,请不要重复导入");
                    }
                    ////物料类型
                    //var listMaterialTypeCodes = Data.Select(s => s.MaterialTypeId).Select(s => s.Trim()).Distinct().ToList();
                    //var dicMaterialType = _pB_MaterialBus.GetQueryable<PB_MaterialType>().Where(w => listMaterialTypeCodes.Contains(w.Code)).ToDictionary(k => k.Id, v => v.Code);

                    ////单位组
                    //var listMeasureCodes = Data.Select(s => s.UnitGroupId).Select(s => s.Trim()).Distinct().ToList();
                    //var dicMeasure = _pB_MaterialBus.GetQueryable<Base_UnitGroup>().Where(w => listMeasureCodes.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);
                    //if (dicMeasure.Count < listMeasureCodes.Count)
                    //{
                    //    foreach (var item in dicMeasure)
                    //    {
                    //        listMeasureCodes.Remove(item.Value);

                    //    }
                    //    return Error("单位组编号不存在！" + String.Join(",", listMeasureCodes.ToArray()));
                    //}
                    ////客户
                    ////var listCusCodes = Data.Select(s => s.CusId).Distinct().Select(s => s.Trim()).Distinct().ToList();
                    ////var dicCus = _pB_MaterialBus.GetQueryable<PB_Customer>().Where(w => listCusCodes.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);

                    ////供应商
                    ////var listSupCodes = Data.Select(s => s.SupId).Distinct().Select(s => s.Trim()).Distinct().ToList();
                    ////var dicSup = _pB_MaterialBus.GetQueryable<PB_Supplier>().Where(w => listSupCodes.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);

                    ////仓库
                    ////var listStorCodes = Data.Select(s => s.StorId).Select(s => s.Trim()).Distinct().ToList();
                    ////var dicStor = _pB_MaterialBus.GetQueryable<Base_Department>().Where(w => listStorCodes.Contains(w.Name) && w.Type == 2).ToDictionary(k => k.Id, v => v.Name);

                    ////实例化Redis操作类
                    //_redisOptions.DbChannel = (int)Redis_Type.redis8;
                    //RedisSetHelper redis = new RedisSetHelper(_redisOptions);
                    //List<string> listredis = new List<string>();
                    //if (RedisSetHelper.Exists("BaseUnitGroupRedis"))
                    //{

                    //}
                    //else
                    //{
                    //    _pB_MaterialBus.AddSetRedis();
                    //}
                    //var Base_DepartmentList = _pB_MaterialBus.GetQueryable<Base_Department>().Where(w => w.Type == 2);
                    //string MateriaTypele = "";
                    //foreach (var item in Data)
                    //{
                    //    if (dicMaterialType.ContainsValue(item.MaterialTypeId.Trim()))
                    //        item.MaterialTypeId = dicMaterialType.FirstOrDefault(w => w.Value.Contains(item.MaterialTypeId.Trim())).Key;
                    //    else
                    //          MateriaTypele+= item.MaterialTypeId.Trim()+",";

                    //        //return Error("物料类型编号不存在！");
                    //    //throw new Exception("物料类型编号不存在！");

                    //    if (dicMeasure.ContainsValue(item.UnitGroupId.Trim()))
                    //    {
                    //        //单位组编号
                    //        string groupId = dicMeasure.FirstOrDefault(w => w.Value.Contains(item.UnitGroupId.Trim())).Key;
                    //        item.UnitGroupId = groupId;
                    //        //仓储单位
                    //        if (!item.storageId.IsNullOrEmpty())
                    //        {
                    //            listredis.Clear();
                    //            listredis.Add(""+ groupId +"_"+ item.storageId +"");
                    //            var res = RedisSetHelper.GetHash("BaseUnitGroupRedis", listredis);
                    //            item.storageId = res.FirstOrDefault().Value;
                    //        }
                    //        //销售单位
                    //        if (!item.saleId.IsNullOrEmpty())
                    //        {
                    //            listredis.Clear();
                    //            listredis.Add("" + groupId + "_" + item.storageId + "");
                    //            var res = RedisSetHelper.GetHash("BaseUnitGroupRedis", listredis);
                    //            item.saleId = res.FirstOrDefault().Value;
                    //        }
                    //        //采购单位
                    //        if (!item.purchaseId.IsNullOrEmpty())
                    //        {
                    //            listredis.Clear();
                    //            listredis.Add("" + groupId + "_" + item.storageId + "");
                    //            var res = RedisSetHelper.GetHash("BaseUnitGroupRedis", listredis);
                    //            item.purchaseId = res.FirstOrDefault().Value;
                    //        }
                    //        //生产单位
                    //        if (!item.productionId.IsNullOrEmpty())
                    //        {
                    //            listredis.Clear();
                    //            listredis.Add("" + groupId + "_" + item.storageId + "");
                    //            var res = RedisSetHelper.GetHash("BaseUnitGroupRedis", listredis);
                    //            item.productionId = res.FirstOrDefault().Value;
                    //        }
                    //    }
                    //    else
                    //    {
                    //        return Error("单位组编号不存在！"+ item.UnitGroupId.Trim());
                    //        //throw new Exception("单位组编号不存在！");
                    //    }
                    //    //if (item.CusId == null)
                    //    //{
                    //    //    item.CusId = null;
                    //    //}
                    //    //else if (dicCus.ContainsValue(item.CusId.Trim()))
                    //    //    item.CusId = dicCus.FirstOrDefault(w => w.Value.Contains(item.CusId.Trim())).Key;
                    //    //else
                    //    //    throw new Exception("客户编号不存在！");

                    //    //if (item.SupId == null)
                    //    //{
                    //    //    item.SupId = null;
                    //    //}
                    //    //else if (dicSup.ContainsValue(item.SupId.Trim()))
                    //    //    item.SupId = dicSup.Keys.ToList()[0].ToString();
                    //    //else
                    //    //    throw new Exception("供应商编号不存在！");

                    //    //if (dicStor.ContainsValue(item.StorId.Trim()))
                    //    //    item.StorId = dicStor.FirstOrDefault(w => w.Value.Contains(item.StorId.Trim())).Key;
                    //    //else
                    //    //    throw new Exception("仓库编号不存在！");
                    //    if (!item.StorId.IsNullOrEmpty())
                    //    {
                    //        var dicStor = Base_DepartmentList.Where(w => w.Name == item.StorId).FirstOrDefault();
                    //        item.StorId = dicStor.Id;
                    //    }
                    //}
                    if (Data.Count > 0)
                    {
                        try
                        {
                           await _pB_MaterialBus.AddDataExlAsync(Data, _redisOptions, _mongodbOptions);
                        }
                        catch (Exception ex)
                        {
                            string ErrLogCollection = "ErrLog";
                            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                            ErrLog err = new ErrLog()
                            {
                                Name = "物料导入",
                                Interface = "/PB/PB_Material/Import",
                                Type = "错误",
                                Time = DateTime.Now,
                                Remark = ex.Message
                            };
                            mongo.Add<ErrLog>(ErrLogCollection, err);
                        }

                        //for (int i = 0; i < Data.Count; i += 1000)
                        //{
                        //    var cList = new List<PB_Material>();
                        //    cList = Data.Take(j).Skip(i).ToList();
                        //    j += 1000;
                        //    await _pB_MaterialBus.AddDataExlAsync(cList);
                        //}
                        ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";
                    }
                }
                if (!flag)
                {
                    return Error(ReturnValue = "数据存在问题！" + ReturnValue);
                }
            }
            catch (Exception EX)
            {
                return Error("数据异常！");
            }

            return Success(ReturnValue);

        }

        /// <summary>
        /// 托盘信息表模板导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoCheckJWT]
        public IActionResult ExportToExcel()
        {
            //创建EXCEL工作薄
            IWorkbook workBook = new XSSFWorkbook();
            //创建sheet1文件表
            ISheet sheet = workBook.CreateSheet("物料信息");

            ISheet sheet2 = workBook.CreateSheet("工序");

            var expDir = string.Format("{0}Export\\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
                    DateTime.Now.ToString("yyyyMM"));

            if (!Directory.Exists(expDir)) Directory.CreateDirectory(expDir);

            string filePath = string.Format("物料导入模板.xlsx", expDir, DateTime.Now.ToString("yyyyMMddHHmmss"));



            #region 创建Excel表头(sheet1)
            //创建表头
            IRow header = sheet.CreateRow(0);

            ICell cell = header.CreateCell(0);
            cell.SetCellValue("物料名称");

            cell = header.CreateCell(1);
            cell.SetCellValue("物料编码");

            cell = header.CreateCell(2);
            cell.SetCellValue("物料简称");

            cell = header.CreateCell(3);
            cell.SetCellValue("物料类型");

            cell = header.CreateCell(4);
            cell.SetCellValue("单位组");

            cell = header.CreateCell(5);
            cell.SetCellValue("仓储单位");

            cell = header.CreateCell(6);
            cell.SetCellValue("销售单位");

            cell = header.CreateCell(7);
            cell.SetCellValue("采购单位");

            cell = header.CreateCell(8);
            cell.SetCellValue("生产单位");

            cell = header.CreateCell(9);
            cell.SetCellValue("工序编号");

            cell = header.CreateCell(10);
            cell.SetCellValue("物料规格");

            cell = header.CreateCell(11);
            cell.SetCellValue("上限数量");

            cell = header.CreateCell(12);
            cell.SetCellValue("下限数量");

            cell = header.CreateCell(13);
            cell.SetCellValue("客户");

            cell = header.CreateCell(14);
            cell.SetCellValue("供应商");

            cell = header.CreateCell(15);
            cell.SetCellValue("仓库");

            cell = header.CreateCell(16);
            cell.SetCellValue("单价");

            cell = header.CreateCell(17);
            cell.SetCellValue("最新单价");

            cell = header.CreateCell(18);
            cell.SetCellValue("最低单价");

            cell = header.CreateCell(19);
            cell.SetCellValue("最高单价");

            cell = header.CreateCell(20);
            cell.SetCellValue("结算单价");

            cell = header.CreateCell(21);
            cell.SetCellValue("理论重量");

            cell = header.CreateCell(22);
            cell.SetCellValue("面积");

            cell = header.CreateCell(23);
            cell.SetCellValue("包装规格");

            cell = header.CreateCell(24);
            cell.SetCellValue("长");

            cell = header.CreateCell(25);
            cell.SetCellValue("宽");

            cell = header.CreateCell(26);
            cell.SetCellValue("高");

            cell = header.CreateCell(27);
            cell.SetCellValue("预估单价");

            cell = header.CreateCell(28);
            cell.SetCellValue("安装位置");

            cell = header.CreateCell(29);
            cell.SetCellValue("材质");

            cell = header.CreateCell(30);
            cell.SetCellValue("是否成品");

            cell = header.CreateCell(31);
            cell.SetCellValue("是否序列号管理");

            cell = header.CreateCell(32);
            cell.SetCellValue("是否自制件");

            cell = header.CreateCell(33);
            cell.SetCellValue("是否劳务");

            cell = header.CreateCell(34);
            cell.SetCellValue("是否数量统计");

            cell = header.CreateCell(35);
            cell.SetCellValue("备注");
            cell = header.CreateCell(36);
            cell.SetCellValue("包装数量");
            cell = header.CreateCell(37);
            cell.SetCellValue("成品编码");

            cell = header.CreateCell(38);
            cell.SetCellValue("是否单个物料");

            cell = header.CreateCell(39);
            cell.SetCellValue("是否半成品");

            #endregion

            #region  创建工序表头（sheet2）
            //创建表头
            IRow header2 = sheet2.CreateRow(0);

            ICell cel2 = header2.CreateCell(0);
            cel2.SetCellValue("工序Id");

            cel2 = header2.CreateCell(1);
            cel2.SetCellValue("工序名称");

            var DeptId = _Op?.Property.DepartmentId;
            List<ProcecureSubTreeListDTO> listdata = new List<ProcecureSubTreeListDTO>();
            var list = _pB_MaterialBus.GetQueryable<PB_ProcecureMain>().Where(x => x.DeptId == DeptId).ToList();
            foreach (var item in list)
            {
                ProcecureSubTreeListDTO tree = new ProcecureSubTreeListDTO();
                tree.Id = item.Id;
                tree.Name = item.Name;
                tree.ParentId = "";
                listdata.Add(tree);
                var listinfo = _pB_MaterialBus.GetQueryable<PB_ProcecureSub>().Where(x => x.ParentId == item.Id).ToList();
                foreach (var iteminfo in listinfo)
                {
                    ProcecureSubTreeListDTO treeinfo = new ProcecureSubTreeListDTO();
                    treeinfo.Id = iteminfo.Id;
                    treeinfo.Name = iteminfo.Name;
                    treeinfo.ParentId = iteminfo.ParentId;
                    listdata.Add(treeinfo);
                }
            }
            for (int i = 0; i < listdata.Count; i++)
            {
                IRow rowData = sheet2.CreateRow(i + 1);
                ICell cel = rowData.CreateCell(0);
                if (!listdata[i].ParentId.ToString().IsNullOrEmpty())
                {
                    cel.SetCellValue(listdata[i].Id.ToString());
                }
                cel = rowData.CreateCell(1);
                cel.SetCellValue(listdata[i].Name.ToString());
            }
            #endregion

            //工作流写入，通过流的方式进行创建生成文件
            using (MemoryStream stream = new MemoryStream())
            {
                workBook.Write(stream);
                byte[] buffer = stream.ToArray();

                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", string.Format("物料导入模板.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")));
            }

        }

        #endregion
        /// <summary>
        /// 通过物料id获取物料信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PB_Material> GetMaterId(string Id) {
            return await _pB_MaterialBus.GetMaterId(Id);
        }
        [HttpPost]
        public async Task UpdateMaterialUsageStatus(UpdateUsageStatus data) {
            await _pB_MaterialBus.UpdateMaterialUsageStatus(data);
        }
        #region 提交

        [HttpPost]
        public async Task SaveData(PB_MaterialProductDTO data)
        {
            if (data.Id.IsNullOrEmpty())
            {
                InitEntity(data);
                //if (data.Code.IsNullOrWhiteSpace())
                //{
                //    data.Code = await _provider.GetRequiredService<IPB_BarCodeTypeBusiness>().Generate("PB_Material");
                //}

                await _pB_MaterialBus.AddDataAsync(data,_redisOptions);
            }
            else
            {
                await _pB_MaterialBus.UpdateDataAsync(data, _redisOptions);
            }
        }

        [HttpPost]
        public async Task DeleteData(List<string> ids)
        {
            await _pB_MaterialBus.DeleteDataAsync(ids);
        }

        /// <summary>
        /// 流水号加1
        /// </summary>
        /// <param name="QrCode"></param>
        /// <returns></returns>
        private string GetCodeNum(string QrCode)
        {
            string number = "";
            if (!QrCode.IsNullOrEmpty())
            {
                string[] arr = QrCode.Split(',');
                number = arr[arr.Length - 1];
                if (number == "99999")
                {
                    number = GetNum(number);
                }
                else if (Regex.Matches(number, "[A-Z]").Count > 0)
                {
                    string letter = number.Substring(0, 1);
                    string rnumber = number.Substring(number.Length - 4, 4);
                    if (rnumber == "9999")
                    {
                        number = GetNum(number);
                    }
                    else
                    {
                        number = letter + "0000" + (Convert.ToInt32(rnumber) + 1).ToString();
                        number = number.Substring(number.Length - 5, 5);
                    }
                }
                else if (Convert.ToInt32(number) < 99999)
                {
                    number = "00000" + (Convert.ToInt32(number) + 1).ToString();
                    number = number.Substring(number.Length - 5, 5);
                }
            }
            else
            {
                number = "00001";
            }
            return number;
        }

        /// <summary>
        /// 流水号最大值时变化流水号的值
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private string GetNum(string number)
        {
            string num = "";
            switch (number)
            {
                case "99999":
                    num = "A0001";
                    break;
                case "A9999":
                    num = "B0001";
                    break;
                case "B9999":
                    num = "C0001";
                    break;
                case "C9999":
                    num = "D0001";
                    break;
                case "D9999":
                    num = "E0001";
                    break;
                case "E9999":
                    num = "F0001";
                    break;
                case "F9999":
                    num = "G0001";
                    break;
                case "G9999":
                    num = "H0001";
                    break;
                case "H9999":
                    num = "I0001";
                    break;
                case "I9999":
                    num = "J0001";
                    break;
                case "J9999":
                    num = "K0001";
                    break;
                case "K9999":
                    num = "L0001";
                    break;
                case "L9999":
                    num = "M0001";
                    break;
                case "M9999":
                    num = "N0001";
                    break;
                case "N9999":
                    num = "O0001";
                    break;
                case "O9999":
                    num = "P0001";
                    break;
                case "P9999":
                    num = "Q0001";
                    break;
                case "Q9999":
                    num = "R0001";
                    break;
                case "R9999":
                    num = "S0001";
                    break;
                case "S9999":
                    num = "U0001";
                    break;
                case "U9999":
                    num = "V0001";
                    break;
                case "V9999":
                    num = "W0001";
                    break;
                case "W9999":
                    num = "X0001";
                    break;
                case "X9999":
                    num = "Y0001";
                    break;
                case "Y9999":
                    num = "Z0001";
                    break;
                default:
                    num = number;
                    break;
            }
            return num;
        }

        #endregion


        #region 物料轨迹跟踪

        /// <summary>
        /// 物料轨迹跟踪
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<MaterialTrajectoryDTO>> GetMaterialTrajectoryList(PageInput<MTConditionDTO> input)
        {
            return await _pB_MaterialBus.GetMaterialTrajectoryListAsync(input);
        }

        #endregion

    }
}